package com.wujunshen.algorithm.leetcode.basic;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2022/7/25 01:18<br>
 */
public class 按奇偶排序数组II {
  public int[] sortArrayByParityII(int[] nums) {
    int even = 0, odd = 1;
    while (true) {
      while (even < nums.length && nums[even] % 2 == 0) {
        even += 2;
      }
      while (odd < nums.length && nums[odd] % 2 != 0) {
        odd += 2;
      }
      if (odd >= nums.length || even >= nums.length) {
        return nums;
      }

      swap(nums, even, odd);
    }
  }

  public void swap(int[] nums, int i, int j) {
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
  }
}
